import { AxiosRequestConfig, AxiosResponse } from "axios";
import { routeMapping, router } from "@/router/index";
import { store, storeCommitPath, storeGetterPath } from "@/store/index";

import APIEndPoint from "@/common/constants/APIConst";
import { HttpClient } from "./HttpClient";
import Settings from "@/common/constants/Settings";
// import SweetAlertService from "@/common/services/SweetAlertService";
// import jsonformdata from "json-form-data";
import jsonformdata from "json-form-data";

const ignoreTokenAPI = [
  APIEndPoint.authentication.login,
  APIEndPoint.authentication.forgotpassword,
  APIEndPoint.authentication.getserver,
];

const useFormDataAPI = [
  APIEndPoint.smi.SaveSMI,
  APIEndPoint.quotation.SaveQuotation,
  APIEndPoint.project.SaveProject,
  APIEndPoint.taskOrder.SaveTaskOrder,
  APIEndPoint.pipe.UpdatePipe,
  APIEndPoint.pipe.AddPipe,
  //APIEndPoint.siteProgress.SavePipeProgresses,
];

export function setupInterceptors() {
  let requestsPending = 0;
  const req = {
    pending: () => {
      requestsPending++;
      // store.commit(storeCommitPath.LoaderStore.show);
    },
    done: () => {
      requestsPending--;
      if (requestsPending <= 0) {
        // store.commit(storeCommitPath.LoaderStore.hide);
      }
    },
  };
  HttpClient.interceptors.request.use(
    (config: AxiosRequestConfig) => {
      req.pending();
      const serverRouter = store.getters[storeGetterPath.baseUrl];

      if (serverRouter) {
        config.baseURL = serverRouter;
      } else {
        config.baseURL = Settings.ServerRouterBaseUrl;
      }

      if (config.url) {
        if (isUseFormDataAPI(config.url)) {
          config = useFormData(config);
        }
      }
      if (config.url) {
        if (isMiddlewareAPI(config.url)) {
          config = addTokenToAxiosConfig(config);
        }
      }
      return config;
    },
    (error: Error) => {
      requestsPending--;
      req.done();
      return Promise.reject(error);
    }
  );
  HttpClient.interceptors.response.use(
    (response: AxiosResponse) => {
      req.done();
      // console.log(store.state.displayPopup);
      if (store.state.displayPopup) {
        if (
          response.data.IsSuccess &&
          !(JSON.stringify(response.data.Data) == "false")
        ) {
          // SweetAlertService.success("Success", response.data.Message);
        } else {
          // SweetAlertService.warning("Warn", response.data.Message);
        }
        // store.commit(storeCommitPath.setDisplayPopup, false);
      } else {
        if (!response.data.IsSuccess) {
          // SweetAlertService.warning("Warn", response.data.Message);
        }
      }
      return Promise.resolve(response);
    },
    (error: Error) => {
      req.done();
      if (error.message == "Request failed with status code 401") {
        // SweetAlertService.error(
        //   "Error",
        //   "User not authenticated, please login again"
        // );
        router.push({ name: routeMapping.Login });
      } else {
        // SweetAlertService.error("Error", error.message);
      }
      // store.commit(storeCommitPath.setDisplayPopup, false);
      return Promise.reject(error);
    }
  );
}

function addTokenToAxiosConfig(config: AxiosRequestConfig) {
  config.headers!.token =
    store.getters[storeGetterPath.AuthenticationStore.accessToken];
  return config;
}

export function useFormData(config: AxiosRequestConfig) {
  config.headers!["Content-Type"] =
    "application/x-www-form-urlencoded; charset=UTF-8";
  const options = {
    initialFormData: new FormData(),
    showLeafArrayIndexes: true,
    includeNullValues: true,
    mapping: function (value: any) {
      if (typeof value === "boolean") {
        return +value ? "true" : "false";
      }
      return value;
    },
  };
  const formData = jsonformdata(config.data, options);
  config.data = formData;
  return config;
}

function isMiddlewareAPI(url: string) {
  let isMiddlewareAPI = true;
  for (let i = 0; i < ignoreTokenAPI.length; i++) {
    if (url.includes(ignoreTokenAPI[i])) {
      isMiddlewareAPI = false;
      break;
    }
  }
  return isMiddlewareAPI;
}

function isUseFormDataAPI(url: string) {
  let isUseFormData = true;
  for (let i = 0; i < useFormDataAPI.length; i++) {
    if (url == useFormDataAPI[i]) {
      isUseFormData = false;
      break;
    }
  }
  return !isUseFormData;
}
